package cn.edu.whut.system.service.impl;

import cn.edu.whut.system.mapper.SysUserMapper;
import cn.edu.whut.system.repository.SysUserRepository;
import cn.edu.whut.system.service.ISysUserService;
import cn.edu.whut.system.vo.user.SysUserReq;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserRepository> implements ISysUserService {

    private final PasswordEncoder passwordEncoder;

    /**
     * 创建用户
     *
     * @param sysUserReq 用户信息
     * @return 创建的用户id
     */
    @Override
    public Integer createUser(SysUserReq sysUserReq) {
        SysUserRepository sysUserRepository = BeanUtil.toBean(sysUserReq, SysUserRepository.class);
        validateUserForCreateOrUpdate(null, sysUserReq.getUsername());
        sysUserRepository.setCreateTime(new Timestamp(System.currentTimeMillis()));
        sysUserRepository.setCreatorId(1);
        sysUserRepository.setPassword(encodePassword(sysUserRepository.getPassword()));
        baseMapper.insert(sysUserRepository);
        return sysUserRepository.getUserId();
    }

    /**
     * 对密码进行加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }

    /**
     * 校验用户信息是否符合要求
     *
     * @param userId   用户id
     * @param username 用户名
     */
    private void validateUserForCreateOrUpdate(Integer userId, String username){
        validateUserExists(userId);
        validateUsernameUnique(userId, username);
    }

    /**
     * 验证用户是否存在
     *
     * @param userId 用户id
     */
    private void validateUserExists(Integer userId) {
        if(userId == null){
            return ;
        }
        SysUserRepository sysUserRepository = baseMapper.selectById(userId);
        if (sysUserRepository == null) {
            throw new RuntimeException("用户不存在");
        }
    }

    /**
     * 验证用户名是否唯一
     *
     * @param userId   用户id
     * @param username 用户名
     */
    private void validateUsernameUnique(Integer userId, String username){
        if(StrUtil.isBlank(username)){
            return;
        }
        SysUserRepository sysUserRepository = baseMapper.findByUsername(username);
        if(sysUserRepository == null){
            return;
        }
        if(userId == null || !userId.equals(sysUserRepository.getUserId())){
            throw new RuntimeException("用户名已存在");
        }
    }
}
